package com.ruoyi.project.pickToBC.demo;

import com.ruoyi.project.WxMoudle.Bases.WeixinConfig;
import com.ruoyi.project.alipay.MD5Utils;
import com.ruoyi.project.alipay.OtherUtils;
import com.ruoyi.project.alipay.WeChatWithdrawUtils;
import com.ruoyi.project.pickToBC.RSAUtils;
import com.ruoyi.project.pickToBC.SendWeChat;
import com.ruoyi.project.pickToBC.WxBase64;
import org.apache.commons.collections.map.HashedMap;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.ResourceUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.*;

import static oshi.util.ParseUtil.byteArrayToHexString;

/*测试使用无实际意义*/
public class PickToBCUtils {

    public static void main(String[] args) throws Exception {
        String str = wxCashBank("23131313546464546464", "6217002870029767967", "尹文浩", "1003", new BigDecimal("1"));
        Map<String,String> resultMap = OtherUtils.readStringXmlOut(str);

        if(resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code",""))){
            System.out.println("提现到银行卡成功");
            System.out.println("返回结果："+str);
        }else{
            System.out.println("提现到银行卡失败");
            System.out.println("返回结果："+str);
        }
    }

    //微信提现到个人银行卡
    public static String wxCashBank(String orderNum, String cardNum, String accountName, String bankCode, BigDecimal amout) throws Exception{
        String nonce_str = getRandomStringByLength(16);//生成随机数，可直接用系统提供的方法
        String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
        PublicKey pub= RSAUtils.getPubKey(WeixinConfig.PUBLIC_PEM_PATH+"/","RSA"); //读取PKCS8密钥文件
        byte[] estr=RSAUtils.encrypt(cardNum.getBytes(),pub,2048, 11,rsa);   //对银行账号进行加密
        String rscardNo = WxBase64.encode(estr);//并转为base64格式
        byte[] estr2=RSAUtils.encrypt(accountName.getBytes(),pub,2048, 11,rsa);   //对银行账号进行加密
        String rsaccountName=WxBase64.encode(estr2);//并转为base64格式


        HashMap<String, String> map = new HashMap<String, String>();

        map.put("mch_id", WeixinConfig.MACHINEDID);  //商户号
        map.put("partner_trade_no", orderNum);//商户订单号（提现id)
        map.put("nonce_str", nonce_str);      //随机字符串

        map.put("enc_bank_no", rscardNo);//收款方银行卡号
        map.put("enc_true_name", rsaccountName);//收款方用户名
        map.put("bank_code", bankCode);//收款方开户行id
        map.put("amount", amout.multiply(new BigDecimal(100)).toString());//上线后需要更改
        String projectName="有有积分";
        map.put("desc", "【"+projectName+"】账户资金提现");
        String returnInfo = SendWeChat.toWeChat(map, WeixinConfig.PAY_TO_BANK);    //请求微信接口
        Map<String, String> resultMap = OtherUtils.readStringXmlOut(returnInfo);
        if (resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code", ""))) {
            System.out.println("提现成功");
            System.out.println("返回结果：" + returnInfo);
            return "success";
        } else {
            System.out.println("提现失败");
            System.out.println("返回结果：" + returnInfo);
            return "fail";
        }
    }


    public static String getRandomStringByLength(int len){
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    public static String getXmlStringFromMap(Map<String, Object> map){
        StringBuffer buffer = new StringBuffer();
        buffer.append("<xml>");
        for (String key : map.keySet()) {
            buffer.append("<").append(key).append(">")
                    .append("<![CDATA[")
                    .append(String.valueOf(map.get(key)))
                    .append("]]>")
                    .append("</").append(key).append(">");
        }
        buffer.append("</xml>");
        return buffer.toString();
    }

    public static Map<String, Object> getMapFromXML(String responseString) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            SAXReader reader = new SAXReader();
            Document doc;
            doc = reader.read(new ByteArrayInputStream(responseString.getBytes("UTF-8")));
//            doc = reader.read(responseString);
            Element root = doc.getRootElement();
            List<Element> list = root.elements();
            for (Element element : list) {
                map.put(element.getName(), element.getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

    //微信签名（需要用户 商户后台 key)
    public static String getSign(Map<String, Object> map){
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(entry.getValue()!="" && !entry.toString().equals("return_code") && !entry.toString().equals("return_msg") && !entry.toString().equals("result_code")){
                System.out.println();
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }

        String result = sb.toString();
        result += "key=商户平台，账户中心,API安全 API密钥";
        System.out.println(result);
        //Util.log("Sign Before MD5:" + result);
        try{
            MessageDigest e = MessageDigest.getInstance("MD5");
            result = byteArrayToHexString(e.digest(result.getBytes("utf-8"))).toUpperCase();
        }catch (Exception e){
            e.printStackTrace();
        }
        //result = MD5.MD5Encode(result).toUpperCase();
        //Util.log("Sign Result:" + result);
        return result;
    }


}

